package com.tree.backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.UserDTO;
import com.tree.backend.entity.dto.UserQueryDTO;
import com.tree.backend.entity.vo.LoginVO;
import com.tree.backend.entity.vo.UserInfoVO;
import com.tree.backend.entity.vo.UserListVO;
import com.tree.backend.entity.vo.UserStatsVO;
import com.tree.backend.service.IUserService;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户控制器
 * </p>
 *
 * @author tree
 * @since 2025-11-04
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    /**
     * 获取用户信息接口
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo() {
        // 从ThreadLocal中获取当前登录的用户名
        String username = UserContext.getUsername();
        UserInfoVO userInfoVO = userService.getUserInfo(username);
        return Result.success(userInfoVO);
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestParam String username, @RequestParam String password) {
        LoginVO loginVO = userService.login(username, password);
        return Result.success(loginVO);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        userService.logout();
        return Result.success("");
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public Result<UserStatsVO> getUserStats() {
        UserStatsVO statsVO = userService.getUserStats();
        return Result.success(statsVO);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public Result<Page<UserListVO>> getUserList(UserQueryDTO queryDTO) {
        Page<UserListVO> userList = userService.getUserList(queryDTO);
        return Result.success(userList);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public Result<Boolean> addUser(@RequestBody UserDTO userDTO) {
        boolean success = userService.addUser(userDTO);
        return Result.success(success);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public Result<Boolean> updateUser(@PathVariable Long userId, @RequestBody UserDTO userDTO) {
        boolean success = userService.updateUser(userId, userDTO);
        return Result.success(success);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public Result<Boolean> deleteUser(@PathVariable Long userId) {
        boolean success = userService.deleteUser(userId);
        return Result.success(success);
    }
}
